package genesis.familytree.server.common.model;

import genesis.familytree.server.common.persistence.DataEntity;
import genesis.familytree.server.modules.sys.model.TreeMenu;

import java.util.ArrayList;
import java.util.List;

/**
 *
 */
public abstract class TreeModel<T extends DataEntity<T>> implements java.io.Serializable {

    private TreeModel<T> parent;
    private T data;
    private String name;
    private boolean isShow;
    private int level;

    private List<TreeModel<T>> children;

    public TreeModel(T data, String name, int level, boolean isShow) {
        this.data = data;
        this.name = name;
        this.level = level;
        this.isShow = isShow;
    }

    public void addChild(TreeModel<T> child) {
        child.parent = this;
        getChildren().add(child);
    }

    public int getId() {
        if(null == data || null == data.getId()) return 0;

        return this.data.getId();
    }

    public boolean getIsShow() {
        if (getId() == 0) {
            return true;
        }

        if(!isShow || !parent.isShow) return false;

        return true;
    }

    public boolean isHasChildren() {
        for (TreeModel<T> child : getChildren()) {
            if(child.getIsShow()) return true;
        }

        return false;
    }

    public T getData() {
        return data;
    }

    public void setData(T data) {
        this.data = data;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }

    public List<TreeModel<T>> getChildren() {
        if (null == children) {
            children = new ArrayList<>();
        }
        return children;
    }


    @Override
    public boolean equals(Object obj) {
        if(obj == null) return false;
        if(TreeMenu.class.isInstance(obj)) return false;

        TreeMenu target = (TreeMenu) obj;

        if(target.getId() < 1) return false;
        if(getId() < 1) return false;

        return target.getId() ==getId();
    }
}
